package com.tourism.config;

/**
 * @Description
 * @Author z
 * @Date 2021-03-02 22:07
 */

import com.tourism.config.handler.*;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;

/**
 * EnableWebSecurity注解使得SpringMVC集成了Spring Security的web安全支持
 * 主要作用就是：
 * 1.登录验证
 * 2.url统一拦截管理
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 自定义登录
     */
    @Resource
    private LoginValidateAuthenticationProvider loginValidateAuthenticationProvider;
    /**
     * 登录成功处理器
     */
    @Resource
    private LoginSuccessHandler successHandler;

    /**
     * 登出处理器11
     */
    @Resource
    private MyLogoutSuccessHandler myLogoutSuccessHandler;
    /**
     * 登录失败处理器
     */
    @Resource
    private LoginFailureHandler failureHandler;
    @Resource
    private JwtRequestFilter jwtRequestFilter;

    @Resource
    private NoLoginAuthenticationEntryPoint noLoginAuthenticationEntryPoint;//请求没有待token或者，token过期了就会走这个方法

    @Resource
    private CustomerRestAccessDeniedHandler customerRestAccessDeniedHandler;

    /**
     * 权限配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //解决跨域问题。cors 预检请求放行,让Spring security 放行所有preflight request（cors 预检请求）
        http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();

        // 配置拦截规则
        http.cors(Customizer.withDefaults()).authorizeRequests()
                .antMatchers("/login", "logout", "/mail/**", "/user/addUser", "/file/**", "/area/get**",
                        "/attraction/get**", "/customLine/get**", "/line/get**",
                        "/hotel/get**", "/attractionEvaluation/get**",
                "/carouselPicture/get**", "/ticket/get**", "/room/get**").permitAll().anyRequest().authenticated();

        // 配置登录功能
        http.formLogin()
                .loginPage("/login").successForwardUrl("/").successHandler(successHandler).failureHandler(failureHandler);
        http.httpBasic().authenticationEntryPoint(noLoginAuthenticationEntryPoint);
        //登录后,访问没有权限处理类
        http.exceptionHandling().accessDeniedHandler(customerRestAccessDeniedHandler);
        // 注销成功跳转首页
        http.logout().logoutSuccessHandler(myLogoutSuccessHandler)
                //不使用session
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 跨站请求伪造,该令牌用于验证授权用户和发起请求者是否是同一个人;
                .csrf().disable();
        //验证请求是否正确
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * 自定义认证数据源
     */
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {

        builder.authenticationProvider(loginValidateAuthenticationProvider);

    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        //修改为添加而不是设置，* 最好改为实际的需要，我这是非生产配置，所以粗暴了一点
        configuration.addAllowedOrigin("*");
        //修改为添加而不是设置
        configuration.addAllowedMethod("*");
        //这里很重要，起码需要允许 Access-Control-Allow-Origin
        configuration.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


}
